package com.viknix.threadpool.manager.cluster.listener;

import com.viknix.threadpool.manager.server.dependence.executor.ThreadPoolManager;
import com.viknix.threadpool.manager.server.dependence.factory.ExecutorFactory;
import com.viknix.threadpool.manager.server.dependence.factory.NameThreadFactory;
import com.viknix.threadpool.manager.cluster.file.FileChangeEvent;
import com.viknix.threadpool.manager.cluster.file.FileWatcher;
import com.viknix.threadpool.manager.cluster.file.WatchFileCenter;
import com.viknix.threadpool.manager.server.dependence.exception.ServerProcessException;
import com.viknix.threadpool.manager.server.dependence.monitor.NotifyCenter;
import com.viknix.threadpool.manager.server.dependence.util.DiskUtils;
import com.viknix.threadpool.manager.server.dependence.util.EnvUtil;
import com.viknix.threadpool.manager.server.dependence.util.InetUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Dongqi
 * @Date: 2021/11/11 13:37
 * @Version 1.0
 * @Description: 项目启动监听器 {@link TpmSpringApplicationRunListener}
 */
@Slf4j
public class StartingApplicationListener implements TpmApplicationListener {

    /**
     * 系统变量的key
     * Tpm 启动模式：stand alone 或者 cluster
     */
    private static final String MODE_PROPERTY_KEY_STAND_MODE = "tpm.mode";

    /**
     * 系统变量的key
     * 本机ip地址
     */
    private static final String LOCAL_IP_PROPERTY_KEY = "tpm.local.ip";

    private static final String TPM_APPLICATION_CONF = "tpm_application_conf";

    private static final Map<String, Object> SOURCES = new ConcurrentHashMap<>();

    /**
     * 用于打印tpm启动日志
     */
    private ScheduledExecutorService scheduledExecutorService;

    private volatile boolean starting;

    @Override
    public void starting() {
        starting = true;
    }

    /**
     * 创建文件目录，
     * 向 EnvUtil 中注入 ConfigurableEnvironment 对象，
     * 初始化系统参数
     *
     * @param environment environment
     */
    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        // 创建文件目录:logs, conf, data
        makeWorkDir();
        // 向 EnvUtil 中注入 ConfigurableEnvironment 对象
        injectEnvironment(environment);

        loadPreProperties(environment);

        // 初始化系统参数
        initSystemProperty();
    }

    /**
     * 打印正在启动日志
     *
     * @param context context
     */
    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        // 读取 cluster.conf 获取集群节点ip列表，并打印日志
        logClusterConf();
        // 打印启动日志
        logStarting();
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {

    }

    /**
     * 已经成功启动，关闭启动日志打印
     *
     * @param context context
     */
    @Override
    public void started(ConfigurableApplicationContext context) {
        starting = false;

        closeExecutor();

        log.info(">>> [😊 Start] Tpm started successfully in {} mode.", System.getProperty(MODE_PROPERTY_KEY_STAND_MODE));
    }

    @Override
    public void running(ConfigurableApplicationContext context) {
    }

    /**
     * 启动过程中出现异常，释放资源
     *
     * @param context   context
     * @param exception 异常信息
     */
    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        starting = false;

        makeWorkDir();

        log.error(">>> [😒 Startup errors] : {}", exception);
        ThreadPoolManager.shutdown();
        WatchFileCenter.shutdown();
        NotifyCenter.shutdown();

        closeExecutor();

        context.close();

        log.error(">>> [😒 Start failed] Tpm failed to start, please see {} for more details.",
                Paths.get(EnvUtil.getTpmHome(), "logs/tpm.log"));
    }

    private void injectEnvironment(ConfigurableEnvironment environment) {
        EnvUtil.setEnvironment(environment);
    }

    private void loadPreProperties(ConfigurableEnvironment environment) {
        try {
            SOURCES.putAll(EnvUtil.loadProperties(EnvUtil.getApplicationConfFileResource()));
            environment.getPropertySources()
                    .addLast(new OriginTrackedMapPropertySource(TPM_APPLICATION_CONF, SOURCES));
            registerWatcher();
        } catch (Exception e) {
            throw new ServerProcessException(ServerProcessException.SERVER_ERROR, e);
        }

    }

    private void registerWatcher() throws ServerProcessException {

        WatchFileCenter.registerWatcher(EnvUtil.getConfPath(), new FileWatcher() {
            @Override
            public void onChange(FileChangeEvent event) {
                try {
                    Map<String, ?> tmp = EnvUtil.loadProperties(EnvUtil.getApplicationConfFileResource());
                    SOURCES.putAll(tmp);
                } catch (IOException ignore) {
                    log.warn(">>> [😒 Failed to monitor file] : {}", ignore);
                }
            }

            @Override
            public boolean interest(String context) {
                return StringUtils.contains(context, "application.properties");
            }
        });
    }

    private void initSystemProperty() {

        if (EnvUtil.getStandaloneMode()) {
            System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, "stand alone");
        } else {
            System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, "cluster");
        }
        System.setProperty(LOCAL_IP_PROPERTY_KEY, InetUtils.getSelfIP());
    }

    private void logClusterConf() {
        if (!EnvUtil.getStandaloneMode()) {
            try {
                // 读取 cluster.conf 获取集群节点ip列表
                List<String> clusterConf = EnvUtil.readClusterConf();
                log.info(">>> [😊 Read cluster conf success] The server IP list of Tpm is {}", clusterConf);
            } catch (IOException e) {
                log.error(">>> [😒 Read cluster conf fail] : {}", e);
            }
        }
    }

    private void closeExecutor() {
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdownNow();
        }
    }

    private void makeWorkDir() {
        String[] dirNames = new String[]{"logs", "conf", "data"};
        for (String dirName : dirNames) {
            log.info(">>> [😊 Tpm Log files] : {}", Paths.get(EnvUtil.getTpmHome(), dirName).toString());
            try {
                DiskUtils.forceMkdir(new File(Paths.get(EnvUtil.getTpmHome(), dirName).toUri()));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    private void logStarting() {
        if (!EnvUtil.getStandaloneMode()) {

            scheduledExecutorService = ExecutorFactory
                    .newSingleScheduledExecutorService(new NameThreadFactory("com.viknix.tpm.core.tpm-starting"));

            scheduledExecutorService.scheduleWithFixedDelay(() -> {
                if (starting) {
                    log.info(">>> 😊 Tpm is starting...");
                }
            }, 1, 1, TimeUnit.SECONDS);
        }
    }

}
